package com.dyzx.hbb.modules.attendance.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseCustomListController;
import com.dyzx.hbb.common.utils.Utils;
import com.dyzx.hbb.modules.attendance.bean.ClockTimeValid;
import com.dyzx.hbb.modules.attendance.entity.*;
import com.dyzx.hbb.modules.attendance.query.AttendanceClockConfigQuery;
import com.dyzx.hbb.modules.attendance.service.*;
import com.dyzx.hbb.modules.attendance.vo.AttendanceClockVO;
import com.dyzx.hbb.modules.attendance.vo.AttendanceConfigUVO;
import com.dyzx.hbb.modules.attendance.vo.AttendanceConfigVO;
import com.dyzx.hbb.modules.attendance.vo.AttendanceWorkShiftVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 考勤配置控制器
 * <p>处理考勤系统中的配置管理、班次设置、人员排班和打卡操作等核心业务逻辑
 * <p>主要职责：
 * <ul>
 * <li>提供考勤配置的CRUD操作接口</li>
 * <li>管理排班班次设置和人员分配</li>
 * <li>实现考勤打卡功能，包括上班、下班打卡</li>
 * <li>处理考勤状态验证和计算</li>
 * <li>提供配置详情、精简列表等查询功能</li>
 * </ul>
 * <p>设计意图：作为考勤管理模块的核心控制器，集成配置管理和考勤操作功能，
 * 为前端提供完整的考勤管理接口服务
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@RestController
@RequestMapping("/attendance/clock/config")
@Tag(name = "11.考勤配置", description = "考勤配置管理接口，包括配置的创建、查询、更新和删除等操作")
public class AttendanceClockConfigController extends BaseCustomListController<AttendanceClockConfigService, AttendanceClockConfig, AttendanceClockConfigQuery> {
    @Autowired
    private AttendanceClockConfigService service;

    @Autowired
    private AttendanceClockWorkShiftService workShiftService;

    @Autowired
    private AttendanceClockUserService userService;

    @Autowired
    private AttendanceClockWorkUserService attendanceWorkUserService;
    @Autowired
    private AttendanceDeviceService deviceService;

    @Override
    protected AttendanceClockConfigService getBaseService() {
        return service;
    }

    @Override
    protected MyLambdaQueryWrapper<AttendanceClockConfig> queryWrapper(AttendanceClockConfigQuery query) {
        return new MyLambdaQueryWrapper<>();
    }

    /**
     * 根据ID查询考勤配置详情
     * @param id 考勤配置ID
     * @return 考勤配置详情信息，包括关联的用户和排班信息
     */
    @GetMapping("/info/{id}")
    @Operation(summary = "查询考勤配置详情", description = "根据ID查询考勤配置的详细信息，包括配置基本信息、关联用户和排班信息")
    public Result<AttendanceConfigUVO> info(@Parameter(description = "考勤配置ID") @PathVariable Long id) {
        AttendanceClockConfig entity = service.getById(id);
        if (entity == null) {
            return Result.error(404, "数据不存在");
        }
        List<Long> userIds = userService.listObjs(new MyLambdaQueryWrapper<AttendanceClockUser>().select(AttendanceClockUser::getUserId).eq(AttendanceClockUser::getConfigId, id));
        AttendanceConfigUVO entityData = new AttendanceConfigUVO();
        entityData.setId(entity.getId());
        entityData.setName(entity.getName());
        String weeks = entity.getWeeks();
        String[] split = weeks.split(",");
        List<String> split1 = List.of(split);
        entityData.setWeeks(split1);
        String deviceIds = entity.getDeviceIds();
        String[] split2 = deviceIds.split(",");
        List<String> split3 = List.of(split2);
        entityData.setDeviceIds(split3);


        if (!userIds.isEmpty()) {
            entityData.setUserIds(userIds);
        } else {
            entityData.setUserIds(new ArrayList<>());
        }
        List<Map<String, Object>> list = workShiftService.listMaps(new MyLambdaQueryWrapper<AttendanceClockWorkShift>().eq(AttendanceClockWorkShift::getConfigId, id));
        List<AttendanceWorkShiftVO> attendanceWorkShiftVOS = BeanUtil.copyToList(list, AttendanceWorkShiftVO.class);
        entityData.setTimes(attendanceWorkShiftVOS);
        return Result.ok(entityData);
    }

    /**
     * 获取考勤配置精简列表
     * @return 考勤配置精简列表，包含ID和名称
     */
    @GetMapping("/mini_list")
    @Operation(summary = "获取考勤配置精简列表", description = "获取所有考勤配置的精简信息，仅包含ID和名称，用于下拉选择")
    public Result<List<Map<String, Object>>> miniList() {
        Long organId= SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<AttendanceClockConfig> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(AttendanceClockConfig::getId).as("value");
        queryWrapper.select(AttendanceClockConfig::getName).as("label");
        queryWrapper.orderByDesc(AttendanceClockConfig::getId);
        queryWrapper.eq(AttendanceClockConfig::getOrganId, organId);
        List<Map<String, Object>> maps = service.listMaps(queryWrapper);
        if (maps.isEmpty()) {
            return Result.error(404, "暂无数据");
        }
        return Result.ok(maps);
    }
    //save

    /**
     * 新增
     */
    @Transactional
    @Operation(summary = "新增")
    @PostMapping
    public Result<Boolean> save(@Valid @RequestBody AttendanceConfigVO entity) {
        if (entity == null) {
            return Result.error("参数不能为空");
        }

        AttendanceClockConfig entityCopy = new AttendanceClockConfig();
        BeanUtil.copyProperties(entity, entityCopy);


        List<AttendanceWorkShiftVO> details = entity.getTimes();
        if (details == null || details.isEmpty()) {
            return Result.error("请添加考勤时间");
        }
        List<String> weeks = entity.getWeeks();
        if (weeks.isEmpty()) {
            return Result.error("请选择考勤时间");
        }
        entityCopy.setWeeks(String.join(",", weeks));


        List<String> deviceIds = entity.getDeviceIds();
        if (deviceIds.isEmpty()) {
            return Result.error("请选择设备编号");
        }
        entityCopy.setDeviceIds(String.join(",", deviceIds));



        if (!details.isEmpty()) {
            AttendanceWorkShiftVO start = details.get(0);
            AttendanceWorkShiftVO end = details.get(details.size() - 1);
            entityCopy.setStartTime(start.getStartTime());
            entityCopy.setEndTime(end.getEndTime());
        }
        List<Long> userIds = entity.getUserIds();
        if (userIds != null && !userIds.isEmpty()) {
            entityCopy.setState(2);
        }

        Long userId = SecurityContextHolder.getUserId();
        entityCopy.setOperatorId(userId);

        Long organId = SecurityContextHolder.getOrganId();
        entityCopy.setOrganId(organId);


        boolean save = getBaseService().save(entityCopy);
        if (save) {
            if (details != null && !details.isEmpty()) {
                List<AttendanceClockWorkShift> listWorkShift = new ArrayList<>();
                for (AttendanceWorkShiftVO detail : details) {
                    AttendanceClockWorkShift item = new AttendanceClockWorkShift();
                    item.setConfigId(entityCopy.getId());
                    item.setStartTime(detail.getStartTime());
                    item.setEndTime(detail.getEndTime());
                    item.setOperatorId(userId);
                    item.setOrganId(organId);
                    listWorkShift.add(item);
                }
                workShiftService.saveBatch(listWorkShift);
            }
            if (userIds != null && !userIds.isEmpty()) {
                List<AttendanceClockUser> listUser = new ArrayList<>();
                for (Long user : userIds) {
                    AttendanceClockUser item = new AttendanceClockUser();
                    item.setUserId(user);
                    item.setOperatorId(userId);
                    item.setConfigId(entityCopy.getId());
                    item.setOrganId(organId);
                }
                userService.saveBatch(listUser);
            }
            workShiftAutoEdit(entityCopy.getId());
        }
        return save ? Result.ok() : Result.error("保存失败");
    }

    @Transactional
    @Operation(summary = "修改")
    @PutMapping
    public Result<Boolean> update(@Valid @RequestBody AttendanceConfigUVO entity) {
        if (entity == null) {
            return Result.error("参数不能为空");
        }

        AttendanceClockConfig entityCopy = service.getById(entity.getId());
        BeanUtil.copyProperties(entity, entityCopy);
        if (entityCopy == null) {
            return Result.error("创建实体对象失败");
        }

        List<AttendanceWorkShiftVO> details = entity.getTimes();
        List<String> weeks = entity.getWeeks();
        if (weeks.isEmpty()) {
            return Result.error("请选择考勤时间");
        }
        entityCopy.setWeeks(String.join(",", weeks));

        if (details == null || details.isEmpty()) {
            return Result.error("请添加考勤时间");
        }

        List<String> deviceIds = entity.getDeviceIds();
        if (deviceIds.isEmpty()) {
            return Result.error("请选择设备编号");
        }
        entityCopy.setDeviceIds(String.join(",", deviceIds));
        if (details.size() > 1) {
            AttendanceWorkShiftVO start = details.get(0);
            AttendanceWorkShiftVO end = details.get(details.size() - 1);
            entityCopy.setStartTime(start.getStartTime());
            entityCopy.setEndTime(end.getEndTime());

        }
        List<Long> userIds = entity.getUserIds();
        if (userIds != null && !userIds.isEmpty()) {
            entityCopy.setState(2);
        }

        Long userId = SecurityContextHolder.getUserId();
        entityCopy.setOperatorId(userId);

        Long organId = SecurityContextHolder.getOrganId();
        entityCopy.setOrganId(organId);


        boolean save = getBaseService().updateById(entityCopy);
        if (save) {
            if (details != null && !details.isEmpty()) {
                List<AttendanceClockWorkShift> listWorkShift = new ArrayList<>();
                for (AttendanceWorkShiftVO detail : details) {
                    AttendanceClockWorkShift item = new AttendanceClockWorkShift();
                    item.setId(detail.getId());
                    item.setConfigId(entityCopy.getId());
                    item.setStartTime(detail.getStartTime());
                    item.setEndTime(detail.getEndTime());
                    item.setOperatorId(userId);
                    item.setOrganId(organId);
                    listWorkShift.add(item);
                }
                workShiftService.saveOrUpdateBatch(listWorkShift);
            }
            if (userIds != null && !userIds.isEmpty()) {

                userService.remove(new MyLambdaQueryWrapper<AttendanceClockUser>().eq(AttendanceClockUser::getOrganId, organId).eq(AttendanceClockUser::getConfigId, entityCopy.getId()));
                List<AttendanceClockUser> listUser = new ArrayList<>();
                for (Long user : userIds) {
                    AttendanceClockUser item = new AttendanceClockUser();
                    item.setUserId(user);
                    item.setOperatorId(userId);
                    item.setConfigId(entityCopy.getId());
                    item.setOrganId(organId);
                    listUser.add(item);
                }
                userService.saveOrUpdateBatch(listUser);
            }
            workShiftAutoEdit(entityCopy.getId());
        }
        return save ? Result.ok() : Result.error("保存失败");
    }


    public void workShiftAutoEdit(Long configId) {
        //    System.out.println("hello world");
        List<AttendanceClockWorkShift> items = new ArrayList<>();
        MyLambdaQueryWrapper<AttendanceClockWorkShift> query = new MyLambdaQueryWrapper<>();
        query.eq(AttendanceClockWorkShift::getDeleted, 0);
        query.eq(AttendanceClockWorkShift::getConfigId, configId);
        List<AttendanceClockWorkShift> list = workShiftService.list(query);
        //    System.out.println("处理多个班次配置");
        int size = list.size();
        // 先处理相邻班次之间的关系
        for (int i = 0; i < size; i++) {
            AttendanceClockWorkShift currentShift = list.get(i);
            AttendanceClockWorkShift nextShift = list.get((i + 1) % size); // 循环获取下一个班次

            Calendar currentEnd = Utils.getFormatCalendar(currentShift.getEndTime());
            Calendar nextStart = Utils.getFormatCalendar(nextShift.getStartTime());

            // 如果是最后一个班次与第一个班次的关系，需要考虑跨天
            if (i == size - 1) {
                nextStart.set(Calendar.DATE, nextStart.get(Calendar.DATE) + 1);
            }

            // 计算当前班次结束和下一班次开始之间的间隔
            long between = DateUtil.between(currentEnd.getTime(), nextStart.getTime(), DateUnit.MINUTE);
            long flip = between / 2;

            // 调整当前班次的结束时间和下一班次的开始时间
            currentEnd.set(Calendar.MINUTE, currentEnd.get(Calendar.MINUTE) + (int) flip - 1);
            nextStart.set(Calendar.MINUTE, nextStart.get(Calendar.MINUTE) - (int) flip);

            // 格式化并设置当前班次的结束时间
            String endClock = DateUtil.format(currentEnd.getTime(), "HH:mm");
            currentShift.setEndClock(endClock);

            // 格式化并设置下一班次的开始时间
            String startClock = DateUtil.format(nextStart.getTime(), "HH:mm");
            nextShift.setStartClock(startClock);

            // System.out.println("班次" + i + "结束时间: " + endClock + ", 班次" + ((i + 1) % size) + "开始时间: " + startClock);

            // 将当前处理的班次添加到items集合中
            items.add(currentShift);
        }

        workShiftService.updateBatchById(items);

    }


    @GetMapping("/clock")
    public Result<Map<String, Object>> getClock() {
        Date startDate = Utils.getFormatDate("00:00");
        Date endDate = Utils.getFormatDate("23:59");

        Long userId = SecurityContextHolder.getUserId();
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<AttendanceClockUser> queryWrapperUser = new MyLambdaQueryWrapper<>();
        queryWrapperUser.eq(AttendanceClockUser::getUserId, userId);
        queryWrapperUser.eq(AttendanceClockUser::getOrganId, organId);
        queryWrapperUser.select(AttendanceClockUser::getConfigId);
        List<Long> longs = userService.listObjs(queryWrapperUser, obj -> {
            return Long.parseLong(obj.toString());
        });
        MyLambdaQueryWrapper<AttendanceClockConfig> query = new MyLambdaQueryWrapper<>();
        query.eq(AttendanceClockConfig::getDeleted, 0);
        query.eq(AttendanceClockConfig::getOrganId, organId);

        query.orderByDesc(AttendanceClockConfig::getState);
        if (!longs.isEmpty()) {
            query.in(AttendanceClockConfig::getId, longs);
            query.eq(AttendanceClockConfig::getState, 2);
        } else {
            query.eq(AttendanceClockConfig::getState, 1);
        }
        query.last("limit 1");
        AttendanceClockConfig config = service.getOne(query);
        if (config == null) {
            return Result.error("请先配置考勤规则");
        }
        List<AttendanceDevice>  devices=getDevice(config.getDeviceIds());
      //  System.out.println(config);
        MyLambdaQueryWrapper<AttendanceClockWorkShift> queryWrapperWork = new MyLambdaQueryWrapper<>();
        queryWrapperWork.eq(AttendanceClockWorkShift::getConfigId, config.getId());
        queryWrapperWork.eq(AttendanceClockWorkShift::getOrganId, organId);
        List<AttendanceClockWorkShift> workShifts = workShiftService.list(queryWrapperWork);
        List<AttendanceClockWorkShift> list = workShifts.stream().filter(item -> {
            long l = System.currentTimeMillis();
            Calendar start = Utils.getFormatCalendar(item.getStartClock());
            Calendar end = Utils.getFormatCalendar(item.getEndClock());
            Date startTime = start.getTime();
            Date endTime = end.getTime();
            if (startTime.getTime() > endTime.getTime()) {
                endTime = DateUtil.offset(endTime, DateField.DAY_OF_MONTH, 1);
            }
            String formatEnd = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:ss");
            String formatStart = DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss");
            System.out.println("now: --------------------" + item.getId() + "------------------------");
            System.out.println("start: " + formatStart + "  end:" + formatEnd);
            return l >= startTime.getTime() && l <= endTime.getTime();
        }).toList();
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> configMap = new HashMap<>();

        configMap.put("name", config.getName());
        configMap.put("id", config.getId());
        configMap.put("description", config.getDescription());
        configMap.put("start_time", config.getStartTime());
        configMap.put("end_time", config.getEndTime());
        configMap.put("state", config.getState());
        configMap.put("weeks", config.getWeeks());
        map.put("config", configMap);
        if (!list.isEmpty()) {
            AttendanceClockWorkShift attendanceWorkShift = list.get(0);
            Map<String, Object> workShiftMap = new HashMap<>();
            workShiftMap.put("id", attendanceWorkShift.getId());
            workShiftMap.put("status", attendanceWorkShift.getStatus());
            workShiftMap.put("start_time", attendanceWorkShift.getStartTime());
            workShiftMap.put("end_time", attendanceWorkShift.getEndTime());
            workShiftMap.put("start_clock", Utils.getFormatDate(attendanceWorkShift.getStartClock()).getTime());
            workShiftMap.put("end_clock", Utils.getFormatDate(attendanceWorkShift.getEndClock()).getTime());

            MyLambdaQueryWrapper<AttendanceClockWorkUser> queryWrapperWorkUser = new MyLambdaQueryWrapper<>();
            queryWrapperWorkUser.select(AttendanceClockWorkUser::getId, AttendanceClockWorkUser::getShiftId, AttendanceClockWorkUser::getUserId, AttendanceClockWorkUser::getConfigId,
                    AttendanceClockWorkUser::getStatus, AttendanceClockWorkUser::getEndStatus, AttendanceClockWorkUser::getEndStatusTime, AttendanceClockWorkUser::getEndTime, AttendanceClockWorkUser::getStartTime, AttendanceClockWorkUser::getStartStatus,

             AttendanceClockWorkUser::getStartStatusTime, AttendanceClockWorkUser::getEndStatusTime, AttendanceClockWorkUser::getEndStatusTime, AttendanceClockWorkUser::getEndStatusTime);
            queryWrapperWorkUser.eq(AttendanceClockWorkUser::getShiftId, attendanceWorkShift.getId());
            queryWrapperWorkUser.eq(AttendanceClockWorkUser::getUserId, userId);
            queryWrapperWorkUser.eq(AttendanceClockWorkUser::getConfigId, config.getId());
            queryWrapperWorkUser.eq(AttendanceClockWorkUser::getOrganId, organId);
            queryWrapperWorkUser.ge(AttendanceClockWorkUser::getUpdateDate, startDate.getTime());
            queryWrapperWorkUser.le(AttendanceClockWorkUser::getUpdateDate, endDate.getTime());
            queryWrapperWorkUser.last("limit 1");
            Map<String, Object> one = attendanceWorkUserService.getMap(queryWrapperWorkUser);



            if (one != null) {
                workShiftMap.put("end", true);
            } else {
                one = new HashMap<>();
                one.put("status", 1);
                workShiftMap.put("end", false);
            }

            map.put("work_user", one);
            map.put("work", workShiftMap);
            map.put("device_ids", devices);

        }
        return Result.ok(map);

    }

    private List<AttendanceDevice> getDevice(String deviceIds) {
        MyLambdaQueryWrapper<AttendanceDevice> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(AttendanceDevice::getDeleted, 0);
        String[] split = deviceIds.split(",");
        List<String> split1 = List.of(split);
        queryWrapper.in(AttendanceDevice::getId, split1);
        return deviceService.list(queryWrapper);
    }

    // 考勤打卡
    @PostMapping("/clock")
    public Result<Boolean> clock(@Valid @RequestBody AttendanceClockVO entity) {
        Long userId = SecurityContextHolder.getUserId();
        Long organId = SecurityContextHolder.getOrganId();
        ClockTimeValid clockTimeValid = getClockTimeValid(entity.getConfigId(), entity.getShiftId(), entity.isEnd());
        long lsys = System.currentTimeMillis();
        //类型: 1-上班, 2-下班, 3-外出, 4-返回
        boolean flag = false;
        if (entity.isEnd()) {

            MyLambdaQueryWrapper<AttendanceClockWorkUser> queryWrapper = new MyLambdaQueryWrapper<>();
            queryWrapper.eq(AttendanceClockWorkUser::getUserId, userId);
            queryWrapper.eq(AttendanceClockWorkUser::getConfigId, entity.getConfigId());
            queryWrapper.eq(AttendanceClockWorkUser::getShiftId, entity.getShiftId());
            queryWrapper.last("limit 1");
            AttendanceClockWorkUser workUser = attendanceWorkUserService.getOne(queryWrapper);
            workUser.setEndTime(lsys);
            workUser.setEndStatus(clockTimeValid.getStatus());
            workUser.setEndStatusTime(clockTimeValid.getTime());
            workUser.setStatus(3);
            workUser.setType(2);
            workUser.setLocation(entity.getLocation());
            workUser.setDeviceId(entity.getDeviceId());
            workUser.setImageId(entity.getImageId());
            flag = attendanceWorkUserService.updateById(workUser);
        } else {
            AttendanceClockWorkUser workUser = new AttendanceClockWorkUser();
            workUser.setUserId(userId);
            workUser.setConfigId(entity.getConfigId());
            workUser.setShiftId(entity.getShiftId());
            workUser.setStartTime(lsys);
            workUser.setStartStatus(clockTimeValid.getStatus());
            workUser.setStartStatusTime(clockTimeValid.getTime());
            workUser.setStatus(2);
            workUser.setType(1);
            workUser.setOperatorId(userId);
            workUser.setOrganId(organId);
            workUser.setLocation(entity.getLocation());
            workUser.setDeviceId(entity.getDeviceId());
            workUser.setImageId(entity.getImageId());
            flag = attendanceWorkUserService.save(workUser);
            if (flag) {
                MyLambdaQueryWrapper<AttendanceClockWorkUser> queryWrapper = new MyLambdaQueryWrapper<>();
                queryWrapper.eq(AttendanceClockWorkUser::getUserId, userId);
                queryWrapper.eq(AttendanceClockWorkUser::getConfigId, entity.getConfigId());
                queryWrapper.eq(AttendanceClockWorkUser::getStatus, 2);
                List<AttendanceClockWorkUser> list = attendanceWorkUserService.list(queryWrapper);
                if (!list.isEmpty()) {
                    list = list.stream().peek(item -> {
                        item.setEndStatus(2);
                        item.setStatus(3);
                    }).toList();
                    attendanceWorkUserService.updateBatchById(list);
                }

            }

        }
        return flag ? Result.ok() : Result.error("打卡失败");
    }

    public ClockTimeValid getClockTimeValid(Long configId, Long shiftId, boolean end) {
        ClockTimeValid result = new ClockTimeValid();
//打卡状态（1-正常，2-迟到，3-早退，4-旷工）
        MyLambdaQueryWrapper<AttendanceClockWorkShift> query = new MyLambdaQueryWrapper<>();
        query.eq(AttendanceClockWorkShift::getDeleted, 0);
        query.eq(AttendanceClockWorkShift::getId, shiftId);
        query.eq(AttendanceClockWorkShift::getConfigId, configId);
        AttendanceClockWorkShift workShift = workShiftService.getOne(query);
        Date sys = new Date();
        Date endClockTime = Utils.getFormatDate(workShift.getEndClock());
        Date endTime = Utils.getFormatDate(workShift.getEndTime());
        Date startClockTime = Utils.getFormatDate(workShift.getStartClock());
        Date startTime = Utils.getFormatDate(workShift.getStartTime());
        if (end) {

            if (sys.getTime() <= endClockTime.getTime() && sys.getTime() >= endTime.getTime()) {
                //1-正常
                long between = DateUtil.between(endTime,sys, DateUnit.MS);
                result.setStatus(1);
                result.setTime(between);
                return result;

            } else if (endTime.getTime() > sys.getTime()) {
                long between = DateUtil.between(sys, endTime, DateUnit.MS);
                //3-早退，
                result.setStatus(3);
                result.setTime(between);
                return result;
            } else {
                //4-旷工
                result.setStatus(4);
                result.setTime(0L);
                return result;
            }

        } else {
            if (sys.getTime() >= startClockTime.getTime() && sys.getTime() <= startTime.getTime()) {
                long between = DateUtil.between(sys, startTime, DateUnit.MS);
                //1-正常
                result.setStatus(1);
                result.setTime(between);
                return result;

            } else if (startTime.getTime() < sys.getTime()) {
                //2-迟到
                long between = DateUtil.between(startTime, sys, DateUnit.MS);
                result.setStatus(2);
                result.setTime(between);
                return result;
            } else {
                //4-旷工
                result.setStatus(4);
                result.setTime(0L);
                return result;
            }
        }
    }
}
